﻿--[[	$Id: caelInterrupt.lua 2556 2012-09-17 07:04:23Z sdkyron@gmail.com $	]]

local _, caelInterrupt = ...

caelInterrupt.eventFrame = CreateFrame("Frame", nil, UIParent)

local playerGuid = nil
local msg = "%s: %s (%s)"
local emo = caelLib.locale == "frFR" and "a interrompu %s. (%s)" or "interrupted %s. (%s)"
local grouped = nil
local lastTimestamp = nil
local lastInterrupted = nil

caelInterrupt.eventFrame:RegisterEvent("PLAYER_LOGIN")
caelInterrupt.eventFrame:RegisterEvent("GROUP_ROSTER_UPDATE")
caelInterrupt.eventFrame:SetScript("OnEvent", function(self, event, timestamp, subEvent, _, sourceGUID, _, _, _, _, destName, _, _, _, spellName, _, extraSpellID, extraSpellName)

	if tostring(GetZoneText()) == "Wintergrasp" or tostring(GetZoneText()) == "Tol Barad" or QueueStatusMinimapButton.status == "active" then return end

	if event == "GROUP_ROSTER_UPDATE" then
		local p = GetNumGroupMembers()
		if not grouped and p > 0 then
			self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
			grouped = true
		elseif grouped and p == 0 then
			self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
			grouped = nil
		end
	elseif event == "PLAYER_LOGIN" then
		playerGuid = UnitGUID("player")
	else
		if subEvent == "SPELL_INTERRUPT" and sourceGUID == playerGuid then
			if timestamp ~= lastTimestamp or extraSpellName ~= lastInterrupted then
				lastTimestamp = timestamp
				lastInterrupted = extraSpellName
				local shortDestName = (string.len(destName) > 12) and string.gsub(destName, "%s?(.[\128-\191]*)%S+%s", "%1. ") or destName
				local emote = emo:format(GetSpellLink(extraSpellID), caelLib.utf8sub(shortDestName, 12, true))
				SendChatMessage(emote, "EMOTE")
			end
		end
	end
end)